<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import dayjs, { type Dayjs } from 'dayjs'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import {
  getNotificationTemplatesApi,
  createNotificationTaskApi,
  type NotificationTemplateItem,
  type NotificationTaskResponse,
  type NotificationTaskCreateParams,
} from '~/api/common/login'

defineOptions({
  name: 'SmsList',
})

interface NotificationTaskView extends NotificationTaskResponse {
  template_name?: string
  notification_label?: string
  status?: 'scheduled' | 'pending' | 'finished'
}

const templateList = ref<NotificationTemplateItem[]>([])
const templateLoading = ref(false)
const taskList = ref<NotificationTaskView[]>([])
const creating = ref(false)
const formRef = ref<FormInstance>()

const formModel = reactive<{
  task_name: string
  template_id?: number
  recipient_type: 1 | 2
  send_scope: 1 | 2
  recipient_list: string
  scheduled_time?: Dayjs
}>({
  task_name: '',
  template_id: undefined,
  recipient_type: 2,
  send_scope: 1,
  recipient_list: '',
  scheduled_time: undefined,
})

const rules: Record<string, Rule[]> = {
  task_name: [{ required: true, type: 'string', message: '请输入任务名称', trigger: 'blur' }],
  template_id: [{ required: true, type: 'number', message: '请选择通知模板', trigger: 'change' }],
  recipient_type: [{ required: true, type: 'number', message: '请选择接收人类型', trigger: 'change' }],
  send_scope: [{ required: true, type: 'number', message: '请选择发送范围', trigger: 'change' }],
  recipient_list: [{
    validator: (_: any, value: string) => {
      if (formModel.send_scope === 1)
        return Promise.resolve()
      if (value && value.trim().length > 0)
        return Promise.resolve()
      return Promise.reject(new Error('请输入接收人手机号 / 账号，使用英文逗号分隔'))
    },
    trigger: 'blur',
    type: 'string',
  }],
}

const recipientTypeOptions = [
  { label: '考生', value: 1 },
  { label: '管理员', value: 2 },
]

const sendScopeOptions = [
  { label: '全部接收人', value: 1 },
  { label: '部分接收人', value: 2 },
]

const notificationTypeMap: Record<number, string> = {
  1: '邮件',
  2: '短信',
  3: '站内信',
}

const selectedTemplate = computed(() => templateList.value.find(item => item.id === formModel.template_id))
const templateSelectOptions = computed(() => templateList.value.map(item => ({ label: item.template_name, value: item.id })))

const dashboardStats = computed(() => {
  const total = taskList.value.length
  const scheduled = taskList.value.filter(item => item.status === 'scheduled').length
  const finished = taskList.value.filter(item => item.status === 'finished').length
  return [
    { label: '全部任务', value: total, sub: '累计创建' },
    { label: '待发送', value: scheduled, sub: '未来24小时' },
    { label: '已完成', value: finished, sub: '成功送达' },
  ]
})

const columns = [
  { title: '任务名称', dataIndex: 'task_name', key: 'task_name' },
  { title: '模板', dataIndex: 'template_name', key: 'template_name' },
  { title: '通知渠道', dataIndex: 'notification_label', key: 'notification_label' },
  { title: '接收人', dataIndex: 'recipient_type', key: 'recipient_type' },
  { title: '范围', dataIndex: 'send_scope', key: 'send_scope' },
  { title: '计划时间', dataIndex: 'scheduled_time', key: 'scheduled_time' },
  { title: '统计', dataIndex: 'total_count', key: 'total_count' },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at' },
]

watch(() => formModel.send_scope, (value) => {
  if (value === 1)
    formModel.recipient_list = ''
})

async function fetchTemplates() {
  templateLoading.value = true
  try {
    const response = await getNotificationTemplatesApi()
    if (response.code === 0 && response.data)
      templateList.value = response.data
    else
      templateList.value = []
  } catch (error) {
    console.error(error)
    templateList.value = []
  } finally {
    templateLoading.value = false
    seedMockTasks()
  }
}

function seedMockTasks() {
  const fallbackTemplates = templateList.value.length ? templateList.value : [{
    id: 1,
    template_code: 'mock',
    template_name: '缴费提醒短信',
    notification_type: 2,
    subject: '',
    content: '',
    description: '',
    status: 1,
    created_at: '',
    updated_at: '',
    created_by: 'system',
  }]

  const now = dayjs()
  taskList.value = [
    {
      id: 101,
      task_name: 'LIBF 考生缴费提醒',
      template_id: fallbackTemplates[0].id,
      template_name: fallbackTemplates[0].template_name,
      notification_type: fallbackTemplates[0].notification_type,
      notification_label: notificationTypeMap[fallbackTemplates[0].notification_type],
      recipient_type: 1,
      recipient_list: null,
      send_scope: 1,
      scheduled_time: now.add(2, 'hour').format('YYYY-MM-DD HH:mm:ss'),
      total_count: 180,
      success_count: 0,
      fail_count: 0,
      created_at: now.subtract(10, 'minute').format('YYYY-MM-DD HH:mm:ss'),
      updated_at: now.subtract(10, 'minute').format('YYYY-MM-DD HH:mm:ss'),
      created_by: 'system',
      status: 'scheduled',
    },
    {
      id: 102,
      task_name: '管理员审核提醒',
      template_id: fallbackTemplates[0].id,
      template_name: fallbackTemplates[0].template_name,
      notification_type: fallbackTemplates[0].notification_type,
      notification_label: notificationTypeMap[fallbackTemplates[0].notification_type],
      recipient_type: 2,
      recipient_list: 'ops01,ops02',
      send_scope: 2,
      scheduled_time: now.add(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
      total_count: 2,
      success_count: 0,
      fail_count: 0,
      created_at: now.subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
      updated_at: now.subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
      created_by: 'automations',
      status: 'scheduled',
    },
    {
      id: 103,
      task_name: '补录材料通知',
      template_id: fallbackTemplates[0].id,
      template_name: fallbackTemplates[0].template_name,
      notification_type: fallbackTemplates[0].notification_type,
      notification_label: notificationTypeMap[fallbackTemplates[0].notification_type],
      recipient_type: 1,
      recipient_list: null,
      send_scope: 1,
      scheduled_time: now.subtract(3, 'day').format('YYYY-MM-DD HH:mm:ss'),
      total_count: 126,
      success_count: 124,
      fail_count: 2,
      created_at: now.subtract(4, 'day').format('YYYY-MM-DD HH:mm:ss'),
      updated_at: now.subtract(3, 'day').format('YYYY-MM-DD HH:mm:ss'),
      created_by: 'finance',
      status: 'finished',
    },
  ]
}

function formatRecipientType(value: number) {
  return value === 1 ? '考生' : '管理员'
}

function formatScope(value: number, list?: string | null) {
  if (value === 1)
    return '全部'
  return list || '部分'
}

function formatStats(row: NotificationTaskView) {
  if (!row.total_count)
    return '--'
  return `${row.success_count}/${row.total_count}`
}

async function handleCreateTask() {
  try {
    await formRef.value?.validate()
    creating.value = true
    const payload: NotificationTaskCreateParams = {
      task_name: formModel.task_name,
      template_id: formModel.template_id!,
      recipient_type: formModel.recipient_type,
      send_scope: formModel.send_scope,
      recipient_list: formModel.send_scope === 1 ? undefined : formModel.recipient_list.trim(),
      scheduled_time: formModel.scheduled_time ? formModel.scheduled_time.format('YYYY-MM-DD HH:mm:ss') : null,
    }
    const response = await createNotificationTaskApi(payload)
    if (response.code === 0 && response.data) {
      const data = response.data
      const template = templateList.value.find(item => item.id === data.template_id)
      taskList.value = [
        {
          ...data,
          template_name: template?.template_name,
          notification_label: template ? notificationTypeMap[template.notification_type] : '',
          status: data.scheduled_time ? 'scheduled' : 'pending',
        },
        ...taskList.value,
      ]
      message.success('通知任务已创建')
      resetForm()
    } else {
      message.error(response.msg || '创建失败')
    }
  } catch (error) {
    const maybeError = error as any
    if (maybeError?.errorFields)
      return
    const errMsg = maybeError?.message || '创建失败，请稍后重试'
    message.error(errMsg)
  } finally {
    creating.value = false
  }
}

function resetForm() {
  formModel.task_name = ''
  formModel.template_id = undefined
  formModel.recipient_type = 2
  formModel.send_scope = 1
  formModel.recipient_list = ''
  formModel.scheduled_time = undefined
}

function formatSchedule(value?: string | null) {
  return value ? value : '立即发送'
}

function getCellValue(record: Record<string, any>, dataIndex: string | number | (string | number)[] | undefined) {
  if (dataIndex === undefined)
    return ''
  if (Array.isArray(dataIndex))
    return dataIndex.reduce<any>((acc, key) => (acc ? acc[key as any] : undefined), record) ?? ''
  return record[dataIndex as keyof typeof record] ?? ''
}

onMounted(() => {
  fetchTemplates()
})
</script>

<template>
  <page-container>
    <div class="notification-page fixed-layout">
      <div class="layout-header">
        <h2>考务通知服务</h2>
        <p>统一管理缴费提醒、审核通知等批量通知任务</p>
      </div>

      <div class="fixed-columns">
        <div class="panel panel-left">
          <div class="panel-scroll">
            <a-card title="发送通知任务" :bordered="false">
              <a-form ref="formRef" :model="formModel" :rules="rules" layout="vertical">
                <a-form-item label="任务名称" name="task_name">
                  <a-input v-model:value="formModel.task_name" placeholder="例如：LIBF 缴费提醒" />
                </a-form-item>
                <a-form-item label="模板选择" name="template_id">
                  <a-select
                    v-model:value="formModel.template_id"
                    placeholder="请选择通知模板"
                    :loading="templateLoading"
                    :options="templateSelectOptions"
                    show-search
                    option-filter-prop="label"
                  />
                </a-form-item>
                <a-form-item label="接收人类型" name="recipient_type">
                  <a-radio-group v-model:value="formModel.recipient_type">
                    <a-radio v-for="option in recipientTypeOptions" :key="option.value" :value="option.value">
                      {{ option.label }}
                    </a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item label="发送范围" name="send_scope">
                  <a-radio-group v-model:value="formModel.send_scope">
                    <a-radio v-for="option in sendScopeOptions" :key="option.value" :value="option.value">
                      {{ option.label }}
                    </a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item v-if="formModel.send_scope === 2" label="部分接收人列表" name="recipient_list">
                  <a-textarea
                    v-model:value="formModel.recipient_list"
                    :rows="3"
                    placeholder="请输入接收人账号 / 手机号，使用英文逗号分隔"
                  />
                </a-form-item>
                <a-form-item label="计划发送时间">
                  <a-date-picker
                    v-model:value="formModel.scheduled_time"
                    show-time
                    style="width: 100%"
                    format="YYYY-MM-DD HH:mm:ss"
                    placeholder="不选择则立即发送"
                  />
                </a-form-item>
                <div class="form-actions">
                  <a-space>
                    <a-button @click="resetForm">
                      重置
                    </a-button>
                    <a-button type="primary" :loading="creating" @click="handleCreateTask">
                      创建并发送
                    </a-button>
                  </a-space>
                </div>
              </a-form>

              <div v-if="selectedTemplate" class="template-preview">
                <div class="preview-header">
                  <div>
                    <div class="preview-title">{{ selectedTemplate.template_name }}</div>
                    <div class="preview-meta">
                      {{ selectedTemplate ? notificationTypeMap[selectedTemplate.notification_type] : '' }}
                      · {{ selectedTemplate?.subject || '' }}
                    </div>
                  </div>
                  <a-tag>
                    模板 ID：{{ selectedTemplate.id }}
                  </a-tag>
                </div>
                <div class="preview-content">
                  {{ selectedTemplate.content }}
                </div>
              </div>
            </a-card>
          </div>
        </div>

        <div class="panel panel-right">
          <div class="panel-scroll">
            <a-card :bordered="false" class="stats-card-wrapper">
              <div class="stat-grid">
                <div v-for="card in dashboardStats" :key="card.label" class="stat-card compact">
                  <div class="stat-label">{{ card.label }}</div>
                  <div class="stat-value">{{ card.value }}</div>
                  <div class="stat-subtitle">{{ card.sub }}</div>
                </div>
              </div>
            </a-card>

            <a-card class="task-card" title="通知任务列表" :bordered="false">
              <a-table
                :columns="columns"
                :data-source="taskList"
                :row-key="(record: NotificationTaskView) => record.id"
                :pagination="{ pageSize: 6, showSizeChanger: false }"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'template_name'">
                    <div class="table-template">
                      <strong>{{ record.template_name || '-' }}</strong>
                      <span>{{ record.template_code }}</span>
                    </div>
                  </template>
                  <template v-else-if="column.key === 'notification_label'">
                    <a-tag>
                      {{ record.notification_label }}
                    </a-tag>
                  </template>
                  <template v-else-if="column.key === 'recipient_type'">
                    {{ formatRecipientType(record.recipient_type) }}
                  </template>
                  <template v-else-if="column.key === 'send_scope'">
                    {{ formatScope(record.send_scope, record.recipient_list) }}
                  </template>
                  <template v-else-if="column.key === 'scheduled_time'">
                    {{ formatSchedule(record.scheduled_time) }}
                  </template>
                  <template v-else-if="column.key === 'total_count'">
                    {{ formatStats(record as NotificationTaskView) }}
                  </template>
                  <template v-else>
                    {{ getCellValue(record, column.dataIndex as any) }}
                  </template>
                </template>
              </a-table>
            </a-card>
          </div>
        </div>
      </div>
    </div>
  </page-container>
</template>

<style scoped>
@import './index.css';
</style>
